<template>
  <div class="app-container">
    <div class="search-container">
      <el-form inline label-width="68px" ref="queryFromRef" :model="queryParams">
        <el-form-item label="上传时间">
          <el-date-picker
            :editable="false"
            class="!w-[240px]"
            v-model="queryParams.createTimeArr"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="截止时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item>
          <el-button class="filter-item" type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="handleResetQuery"> <i-ep-refresh />重置 </el-button>
          <el-button
            v-hasPerm="['sys:file:saveConfig']"
            type="info"
            @click="handleFileUploadConfig()"
          >
            <template #icon><i-ep-setting /></template>
            文件上传配置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never" class="table-container">
      <template #header>
        <el-upload
          v-model:file-list="fileList"
          class="upload-demo"
          action="#"
          :before-upload="beforeUpload"
          multiple="false"
          :limit="1"
        >
          <el-button v-hasPerm="['sys:file:uploadFile']" type="success" @click="handleUploadFile()">
            <template #icon><i-ep-upload /></template>
            上传文件
          </el-button>
        </el-upload>
      </template>

      <el-table v-loading="loading" stripe :data="list" style="width: 100%">
        <el-table-column label="ID" width="50" prop="id" />
        <el-table-column label="文件路径" width="800" prop="url">
          <template #default="scope">
            <el-link type="primary" :href="scope.row.url" target="_blank">{{
              scope.row.url
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="大小" width="80" prop="fileSize" />
        <el-table-column label="类型" width="150" prop="contentType" />
        <el-table-column label="原始名称" width="240" prop="originalFilename" />
        <el-table-column label="上传时间" width="240" prop="createTime" />
        <el-table-column label="上传人" width="100" prop="createBy" />
        <el-table-column fixed="right" label="操作" width="160">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:file:delete']"
              type="danger"
              link
              size="small"
              @click.stop="handleDelete(scope.row.id)"
              on-success="handleSuccess()"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <el-drawer v-model="dialog.visible" title="文件上传配置" @close="handleCloseDialog" size="50%">
      <el-form ref="addFormRef" :model="formData" label-width="100px">
        <el-form-item label="存储类型">
          <el-radio-group v-model="formData.storageType">
            <el-radio value="local">本地存储</el-radio>
            <el-radio value="qiniu">七牛云存储</el-radio>
            <el-radio value="ali">阿里云存储</el-radio>
            <el-radio value="tencent">腾讯云存储</el-radio>
            <el-radio value="fastDfs">FastDFS存储</el-radio>
            <el-radio value="minIO">MinIO存储</el-radio>
          </el-radio-group>
        </el-form-item>

        <template v-if="formData.storageType === 'local'">
          <el-form-item label="域名" label-width="200px">
            <el-input
              v-model="formData.localFormDTO.domain"
              placeholder="绑定的域名，如：http://cdn.xxx.com"
            />
          </el-form-item>
          <el-form-item label="路径前缀" label-width="200px">
            <el-input v-model="formData.localFormDTO.urlPrefix" placeholder="不设置默认为空" />
          </el-form-item>
          <el-form-item label="本地路径" label-width="200px">
            <el-input v-model="formData.localFormDTO.rootPath" placeholder="如：D:/upload" />
          </el-form-item>
        </template>

        <template v-if="formData.storageType === 'qiniu'">
          <el-form-item label="域名" label-width="200px">
            <el-input v-model="formData.qiniuFormDTO.domain" />
          </el-form-item>
          <el-form-item label="路径前缀" label-width="200px">
            <el-input v-model="formData.qiniuFormDTO.prefix" />
          </el-form-item>
          <el-form-item label="七牛AccessKey" label-width="200px">
            <el-input v-model="formData.qiniuFormDTO.accessKey" />
          </el-form-item>
          <el-form-item label="七牛SecretKey" label-width="200px">
            <el-input v-model="formData.qiniuFormDTO.secretKey" />
          </el-form-item>
          <el-form-item label="七牛存储空间名" label-width="200px">
            <el-input v-model="formData.qiniuFormDTO.bucketName" />
          </el-form-item>
        </template>

        <template v-if="formData.storageType === 'ali'">
          <el-form-item label="域名" label-width="200px">
            <el-input v-model="formData.aliFormDTO.domain" />
          </el-form-item>
          <el-form-item label="路径前缀" label-width="200px">
            <el-input v-model="formData.aliFormDTO.prefix" />
          </el-form-item>
          <el-form-item label="阿里云EndPoint" label-width="200px">
            <el-input v-model="formData.aliFormDTO.endPoint" />
          </el-form-item>
          <el-form-item label="阿里云AccessKeyId" label-width="200px">
            <el-input v-model="formData.aliFormDTO.accessKeyId" />
          </el-form-item>
          <el-form-item label="阿里云AccessKeySecret" label-width="200px">
            <el-input v-model="formData.aliFormDTO.accessKeySecret" />
          </el-form-item>
          <el-form-item label="阿里云BucketName" label-width="200px">
            <el-input v-model="formData.aliFormDTO.bucketName" />
          </el-form-item>
        </template>

        <template v-if="formData.storageType === 'tencent'">
          <el-form-item label="域名" label-width="200px">
            <el-input v-model="formData.tencentFormDTO.domain" />
          </el-form-item>
          <el-form-item label="路径前缀" label-width="200px">
            <el-input v-model="formData.tencentFormDTO.prefix" />
          </el-form-item>
          <el-form-item label="腾讯云AppId" label-width="200px">
            <el-input v-model="formData.tencentFormDTO.appId" />
          </el-form-item>
          <el-form-item label="腾讯云SecretId" label-width="200px">
            <el-input v-model="formData.tencentFormDTO.secretId" />
          </el-form-item>
          <el-form-item label="腾讯云SecretKey" label-width="200px">
            <el-input v-model="formData.tencentFormDTO.secretKey" />
          </el-form-item>
          <el-form-item label="腾讯云BucketName" label-width="200px">
            <el-input v-model="formData.tencentFormDTO.bucketName" />
          </el-form-item>
          <el-form-item label="腾讯云所属地区" label-width="200px">
            <el-select
              v-model="formData.tencentFormDTO.region"
              clearable
              placeholder="请选择"
              class="w-percent-100"
            >
              <el-option value="ap-beijing-1" label="北京一区（华北）" />
              <el-option value="ap-beijing" label="北京" />
              <el-option value="ap-shanghai" label="上海（华东）" />
              <el-option value="ap-guangzhou" label="广州（华南）" />
              <el-option value="ap-chengdu" label="成都（西南）" />
              <el-option value="ap-chongqing" label="重庆" />
              <el-option value="ap-singapore" label="新加坡" />
              <el-option value="ap-hongkong" label="香港" />
              <el-option value="na-toronto" label="多伦多" />
              <el-option value="eu-frankfurt" label="法兰克福" />
            </el-select>
          </el-form-item>
        </template>

        <template v-if="formData.storageType === 'fastDfs'">
          <el-form-item label="域名" label-width="200px">
            <el-input
              v-model="formData.fastDfsFormDTO.domain"
              placeholder="绑定的域名，如：http://cdn.xxx.com"
            />
          </el-form-item>
        </template>

        <template v-if="formData.storageType === 'minIO'">
          <el-form-item label="EndPoint" label-width="200px">
            <el-input
              v-model="formData.minIOFormDTO.endPoint"
              placeholder="MinIO EndPoint，如：ndPoint，如：URL_ADDRESS27.0.0.1:9000"
            />
          </el-form-item>
          <el-form-item label="AccessKey" label-width="200px">
            <el-input v-model="formData.minIOFormDTO.accessKey" />
          </el-form-item>
          <el-form-item label="SecretKey" label-width="200px">
            <el-input v-model="formData.minIOFormDTO.secretKey" />
          </el-form-item>
          <el-form-item label="BucketName" label-width="200px">
            <el-input v-model="formData.minIOFormDTO.bucketName" />
          </el-form-item>
          <el-form-item label="路径前缀" label-width="200px">
            <el-input v-model="formData.minIOFormDTO.prefix" placeholder="不设置默认为空" />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
defineOptions({
  name: 'File',
  inheritAttrs: false
})
import { ElForm, ElTable } from 'element-plus'
import { ref, reactive, onMounted } from 'vue'
import request from '@/utils/request'
const BASE_URL = '/api/yyplatform/admin/sys/file/'
// ============================================================

const list = ref([])
const total = ref(0)

const loading = ref(false)
const queryParams = reactive({
  createTimeArr: [],
  pageNum: 1,
  pageSize: 10
})

function handleDelete(id) {
  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request({
      url: `${BASE_URL}/delete`,
      method: 'post',
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      data: {
        id: id
      }
    }).then(async () => {
      await handleQuery()
    })
  })
}

async function handleQuery() {
  loading.value = true

  let queryRes = await request({
    url: `${BASE_URL}/query`,
    method: 'get',
    params: queryParams
  })

  loading.value = false
  list.value = queryRes.content
  total.value = parseInt(queryRes.totalElements)
}

function handleResetQuery() {
  console.log('handleResetQuery')
  queryParams.value = {
    pageNum: 1,
    pageSize: 20,
    createTimeArr: []
  }
  handleQuery()
}

// ============================================================
const fileList = ref([])

function beforeUpload(file) {
  const formData = new FormData()
  formData.append('file', file)
  request({
    url: `${BASE_URL}/uploadFile`,
    // '/api/yyplatform/admin/sys/file/uploadFile',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then((res) => {
    console.log(res, '上传成功')
    handleQuery()
  })
  return false
}
// ============================================================
const dialog = ref({
  visible: false
})
const addFormRef = ref(ElForm)
const formData = ref({
  storageType: 'local'
})
async function handleFileUploadConfig() {
  let res = await request({
    url: `${BASE_URL}/config/get`,
    method: 'get'
  })
  dialog.value.visible = true
  formData.value = res
}
function handleCloseDialog() {
  dialog.value.visible = false
}
async function submitForm() {
  console.log('submit form')
  let res = await request({
    url: `${BASE_URL}/config/save`,
    method: 'post',
    data: formData.value
  })

  dialog.value.visible = false
}
// ============================================================

onMounted(async () => {
  await handleQuery()
})
</script>

<style lang="css">
.lmr2 {
  margin-left: 10px;
}
.bt1 {
  margin-top: -5px;
  margin-left: 10px;
}
.upload-demo {
  display: inline-block;
}
</style>
